package com.docmgmt.mvp.ragflow;

import com.docmgmt.mvp.entity.FileEntity;
import com.docmgmt.mvp.mapper.FileMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 上传文档到 RAGFlow 知识库
 * 
 * 查询用户有权限的文档，并上传到 RAGFlow
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UploadDocumentsService implements CommandLineRunner {

    @Autowired(required = false)
    private RAGFlowClient ragflowClient;

    @Autowired(required = false)
    private FileMapper fileMapper;

    @Override
    public void run(String... args) throws Exception {
        // 仅在启动时执行一次（可通过环境变量控制）
        String uploadDocs = System.getenv("UPLOAD_DOCS");
        if (!"true".equals(uploadDocs)) {
            log.debug("跳过文档上传（设置 UPLOAD_DOCS=true 启用）");
            return;
        }

        if (ragflowClient == null || fileMapper == null) {
            log.warn("RAGFlowClient 或 FileMapper 未初始化，跳过文档上传");
            return;
        }

        try {
            uploadDocuments();
        } catch (Exception e) {
            log.error("上传文档失败", e);
        }
    }

    /**
     * 上传文档到 RAGFlow
     */
    public void uploadDocuments() {
        String kbId = "64cb2314bbe011f08e7e6ab8e68c840f";
        Long userId = 12L;  // cachetest2 用户 ID
        Long deptId = 1L;   // 部门 ID

        log.info("========================================");
        log.info("开始上传文档到 RAGFlow 知识库");
        log.info("知识库 ID: {}", kbId);
        log.info("用户 ID: {}", userId);
        log.info("部门 ID: {}", deptId);
        log.info("========================================");

        try {
            // 查询用户有权限的文档
            log.info("查询用户有权限的文档...");
            List<FileEntity> accessibleFiles = fileMapper.selectAccessibleDocsForGlobal(userId, deptId);

            log.info("查询到文件数量: {}", accessibleFiles.size());
            
            if (accessibleFiles.isEmpty()) {
                log.warn("⚠️ 用户没有可访问的文档");
                return;
            }

            // 显示文件列表
            log.info("========================================");
            log.info("用户有权限的文档列表:");
            log.info("========================================");
            
            int index = 1;
            for (FileEntity file : accessibleFiles) {
                log.info("{}. ID={}, 名称={}, 隐私级别={}, RAGFlow Doc ID={}",
                        index++,
                        file.getId(),
                        file.getFileName(),
                        file.getPrivacyLevel(),
                        file.getRagflowDocId());
            }

            log.info("========================================");
            log.info("✅ 查询完成，共 {} 个文档", accessibleFiles.size());
            log.info("========================================");

        } catch (Exception e) {
            log.error("❌ 上传文档失败: {}", e.getMessage(), e);
            throw e;
        }
    }
}

